package com.perfect.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.perfect.base.BaseService;
import com.perfect.dao.BrandMapper;
import com.perfect.query.BrandQuery;
import com.perfect.utils.AssertUtil;
import com.perfect.vo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class BrandService extends BaseService<Brand, Integer> {
    @Resource
    private BrandMapper brandMapper;

    //多条件查询
    public Map<String, Object> selectByParams(BrandQuery brandQuery) {

        // System.out.println( brandMapper.selectByParams(brandQuery));

        Map<String, Object> map = new HashMap<>();
        // 开启分页
        PageHelper.startPage(brandQuery.getPage(), brandQuery.getLimit());
        // 得到对应分页对象
        PageInfo<Brand> pageInfo = new PageInfo<>(brandMapper.selectByParams(brandQuery));
// 设置map对象
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", pageInfo.getTotal());
// 设置分页好的列表
        map.put("data", pageInfo.getList());

        return map;

    }


    //添加品牌
    @Transactional(propagation = Propagation.REQUIRED)
    public void addBrand(Brand brand) {
        /* 1. 校验参数 */
        checkSaleChanceParams(brand.getBrandName(), brand.getBrandState(), brand.getBrandPublicity());

// createDate创建时间 默认是系统当前时间
        brand.setBrandCreatetime(new Date());
// updateDate 默认是系统当前时间
        brand.setBrandUpdatetime(new Date());

// 3. 执行添加操作，判断受影响的行数
        AssertUtil.isTrue(brandMapper.insertSelective(brand) != 1, "添加品牌方失败！");


    }


    private void checkSaleChanceParams(String brandName, String brandState, String brandPublicity) {
        // customerName客户名称    非空
        AssertUtil.isTrue(StringUtils.isBlank(brandName), "品牌名称不能为空！");
// linkMan联系人           非空
        AssertUtil.isTrue(StringUtils.isBlank(brandState), "品牌状态不能为空");
        // linkPhone联系号码       非空
        AssertUtil.isTrue(StringUtils.isBlank(brandPublicity), "品牌知名度不能为空！");

    }


    //修改品牌
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateBrand(Brand brand) {

        AssertUtil.isTrue(null == brand.getBrandId(), "待更新记录不存在！");
        // 通过主键查询对象
        Brand temp = brandMapper.selectByPrimaryKey(brand.getBrandId());
// 判断数据库中对应的记录存在
        AssertUtil.isTrue(temp == null, "待更新记录不存在！");
// 参数校验
        checkSaleChanceParams(brand.getBrandName(), brand.getBrandState(), brand.getBrandPublicity());


        /* 2. 设置相关参数的默认值 */
        // updateDate更新时间  设置为系统当前时间
        brand.setBrandUpdatetime(new Date());

        /* 3. 执行更新操作，判断受影响的行数 */
        AssertUtil.isTrue(brandMapper.updateByPrimaryKeySelective(brand) != 1, "更新营销机会失败！");


    }


}
